<?php
/**
 * Description of AlbumRepository
 *
 * @author Martin Grossmann <snake.aas@gmail.com>
 * @version 1.0
 * @package EntityRepository
 */
class AlbumRepository extends \Doctrine\ORM\EntityRepository {
  
  public function getAlbumUnlogged() {
    return $this->_em->createQuery("SELECT a FROM Album a WHERE a.protectionName = 'public' OR a.protectionName = 'password'")->getResult();
  }
  
  public function getAllAlbums($idParent = null) {
    
    $str = '';
    if ($idParent == null) 
      $str = 'IS NULL';
    else
      $str = '= '.$idParent;
      
    $query = $this->_em->createQuery("SELECT a FROM Album a WHERE a.parentAlbum $str");
    return $query->getResult();    
    
  }
  
  public function getAccessibleAlbums(User &$user, Album &$album) {
    $ret = array();    
    foreach ($album->ChildrenAlbums as $alb) {
      if (($alb->ProtectionName == 'private') && !$alb->AllowedUsers->contains($user)) continue;
      $ret[] = $alb;
    }
    
    return $ret;
    
  }  
  
  public function getFreeAlbums($idParent = null) {
    
    $str = '';
    if ($idParent == null) 
      $str = 'IS NULL';
    else
      $str = '= '.$idParent;
      
    $query = $this->_em->createQuery("SELECT a 
                                      FROM Album a 
                                      WHERE a.parentAlbum $str AND 
                                            (a.protectionName = 'public ' OR a.protectionName = 'password')");
    return $query->getResult();    
    
  }
  
  public function getAllAlbumsByUser($idUser, $parentOnly = true) {
    $str = '';
    if($parentOnly) 
      $str = ' AND a.parentAlbum IS NULL';
    
    $query = $this->_em->createQuery("SELECT a FROM Album a WHERE a.user = ?1$str");
    $query->setParameter(1, $idUser);
    return $query->getResult();
    
  }
  
  public function getAccessibleAlbumsByUser($idRequiredUser, User &$user) {
    $query = $this->_em->createQuery("SELECT a FROM Album a WHERE a.user = ?1 AND a.parentAlbum IS NULL");
    $query->setParameter(1, $idRequiredUser);
    $result = $query->getResult();
    
    $ret = array();
    foreach ($result as $alb) {
      if (($alb->ProtectionName == 'private') && !$alb->AllowedUsers->contains($user)) continue;
      $ret[] = $alb;
    }
    
    return $ret;
  }
  
  public function getFreeAlbumsByUser($idUser) {
    $query = $this->_em->createQuery("SELECT a 
                                      FROM Album a 
                                      WHERE a.user = ?1 AND 
                                            a.parentAlbum IS NULL AND
                                            (a.protectionName = 'public ' OR a.protectionName = 'password')");
    $query->setParameter(1, $idUser);
    return $query->getResult();
  }
  
}

?>
